<template>
  <el-dialog
    title="分配权限"
    :visible="showPermDialog"
    @close="handleCloseThis"
  >
    <!-- 权限是一颗树 -->
    <!-- 将数据绑定到组件上 -->
    <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
    <!-- id作为唯一标识 -->
    <el-tree
      ref="permTree"
      :data="permData"
      :props="defaultProps"
      :show-checkbox="true"
      :check-strictly="true"
      :default-expand-all="true"
      :default-checked-keys="selectCheck"
      node-key="id"
    />
    <!-- 确定 取消 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click="handleAssign"
        >确定</el-button>
        <el-button size="small" @click="handleCloseThis">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { formatTree } from '@/utils/tree'
import { assignRoleAPI } from '@/api/settings'
import { getPermissionListAPI } from '@/api/permission'
import { getUserRolesAPI } from '@/api/roles'

export default {
  props: {
    showPermDialog: {
      default: false,
      type: Boolean
    },
    roleId: String
  },
  data() {
    return {
      permData: [], // 专门用来接收权限数据 树形数据
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      defaultProps: {
        label: 'name'
      }
    }
  },
  watch: {
    // id变化时重新获取权限
    roleId() {
      this.getUserRolesFn()
    }
  },
  created() {
    this.getPermissionListFn()
  },
  methods: {
    async getPermissionListFn() {
      const list = await getPermissionListAPI()
      this.permData = formatTree(list, '0')
    },
    async getUserRolesFn() {
      /*
      ? 今日一坑
      ? 直接 this.selectCheck = [] 无法清空树形的选中数据
    */
      if (this.$refs.permTree) this.$refs.permTree.setCheckedKeys([])
      this.selectCheck = (await getUserRolesAPI(this.roleId)).permIds
    },
    // 关闭弹层
    handleCloseThis() {
      this.$emit('update:showPermDialog', false)
    },
    // 提交
    async handleAssign() {
      try {
        const newCheck = this.$refs.permTree.getCheckedKeys()
        await assignRoleAPI({ id: this.roleId, permIds: newCheck })
        this.$message.success('操作成功')
        this.handleCloseThis()
      } catch (e) {
        this.$message.info(e)
      }
    }
  }
}
</script>
